import 'package:flustars/flustars.dart';
import 'package:flutter_nb_net/flutter_net.dart';
import 'package:tracker/common/log/x_logger.dart';
import 'package:tracker/pages/home/location/model/monitor_data_resp.dart';
import 'package:tracker/pages/home/track/model/reverse_geocoding_resp.dart';
import 'package:tracker/pages/home/track/model/track_record_resp.dart';

class TrackApi {
  /// 获取设备实时信息
  static Future<MonitorDataResp> getDeviceMonitor(String imei) async {
    final res = await get<MonitorDataResp, MonitorDataResp>('/monitor/${imei}', decodeType: MonitorDataResp());
    return res.when(success: (resp) {
      return resp;
    }, failure: (String msg, int code) {
      XLogger.error('获取设备实时信息失败：msg: $msg, code: $code');
      return MonitorDataResp();
    });
  }

  static Future<String> reverseGeoCode(double? latitude, double? longitude, String? gpsDataId) async {
    String locationDesc = '';
    final res = await post<ReverseGeocodingResp, ReverseGeocodingResp>('/track/reverseGeocoding',
        data: {
          'latitude': latitude,
          'longitude': longitude,
          'gpsDataId': gpsDataId,
        },
        decodeType: ReverseGeocodingResp());
    res.when(success: (resp) {
      if (resp.code == 200) {
        if (resp.data != null) {
          locationDesc = resp.data!.locationDesc ?? '';
        }
      }
    }, failure: (String msg, int code) {
      XLogger.error('逆地址解析失败：msg: $msg, code: $code');
    });
    return locationDesc;
  }

  /// 获取轨迹日历
  static Future<List<DateTime>> getTrackCalendar(String imei, DateTime beginDate, DateTime endDate) async {
    var postData = {
      'imei': imei,
      'beginMonthDate': DateUtil.formatDate(beginDate, format: 'yyyy-MM'),
      'monthDate': DateUtil.formatDate(endDate, format: 'yyyy-MM'),
      'locationTypes': [1]
    };
    var res = await post<TrackRecordResp, TrackRecordResp>('/track/recordExistByMonth',
        data: postData, decodeType: TrackRecordResp());
    return res.when(success: (resp) {
      if (resp.code == 200 && resp.data != null && resp.data!.isNotEmpty) {
        XLogger.info(resp);

        XLogger.info(resp.data!.entries.where((element) => element.value).map((e) => DateUtil.getDateTime(e.key)!).toList());
        return resp.data!.entries.where((element) => element.value).map((e) => DateUtil.getDateTime(e.key)!).toList();
      }
      XLogger.info('当月无轨迹');
      return [];
    }, failure: (String msg, int code) {
      XLogger.error('查询当月轨迹日历失败：msg: $msg, code: $code');
      return [];
    });
  }
}
